package com.stockz.core.manager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.stockz.core.dao.ConfigurationDao;
import com.stockz.core.model.Configuration;

@Service
@Transactional
public class ConfigurationManager{

	@Autowired
	private ConfigurationDao configurationDao;
	private final  Map<String,String> configurationMap = new HashMap<String,String>();
	
	@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true)
	public List<Configuration> getAllConfiguration(){
		return configurationDao.getAllConfiguration();
	}
	
	private static boolean allConfigurationFetched = false;
	public String getValue(String key){
		if(!allConfigurationFetched){
			List<Configuration> configurationList = configurationDao.getAllConfiguration();
			if(configurationList != null && !configurationList.isEmpty()){
				for(Configuration configuration : configurationList){
					configurationMap.put(configuration.getKey(), configuration.getValue());
				}
			}
			allConfigurationFetched = true;
		}
		return configurationMap.get(key);
	}
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void persist(String key, String value){
		if(StringUtils.hasText(key)){
			Configuration configuration = new Configuration(key,value);
			if(value != null){
				Object oldValue = getValue(key);
				if(oldValue != null){
					configurationDao.merge(configuration);
				}else{
					configurationDao.persist(configuration);
				}
				configurationMap.put(key, value);
			}else{
				configurationDao.remove(configuration);
				configurationMap.remove(key);
			}
		}
	}
	
}
